package com.imooc.ecommerce.service;

import com.alibaba.fastjson.JSON;
import com.imooc.ecommerce.entity.EcommerceLogistics;
import com.imooc.ecommerce.mapper.EcommerceLogisticsMapper;
import com.imooc.ecommerce.order.LogisticsMessage;
import com.imooc.ecommerce.sink.LogisticsSink;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Payload;

/**
 * 物流服务实现
 * @author zhangshao
 * @since 2023/12/15 23:35
 */
@Slf4j
@EnableBinding(LogisticsSink.class)
public class LogisticsServiceImpl {

    @Autowired
    private EcommerceLogisticsMapper logisticsMapper;

    /**
     * 订阅监听订单微服务发送的物流信息
     * @param payload
     */
    @StreamListener("logisticsInput")
    public void consumeLogisticsMessage(@Payload Object payload){
        log.info("receive and consume logistics message :[{}]",payload.toString());
        LogisticsMessage logisticsMessage = JSON.parseObject(payload.toString(), LogisticsMessage.class);
        EcommerceLogistics ecommerceLogistics = new EcommerceLogistics(logisticsMessage.getUserId(),logisticsMessage.getOrderId(),logisticsMessage.getAddressId(),logisticsMessage.getExtraInfos());
        logisticsMapper.insert(
                ecommerceLogistics
        );
        log.info("consume logistics message success : [{}]",ecommerceLogistics.getId());

    }
}
